<template>
  <div class="doctor-table">
    <!-- 页面标题与操作栏 -->
    <div class="header-container">
      <h2 class="page-title">医师管理</h2>
      <div class="action-buttons">
        <button class="btn-add" @click="openAddDialog">
          <i class="fa fa-plus"></i> 添加医师
        </button>
      </div>
    </div>

    <!-- 搜索框区域 -->
    <input v-model="searchKeyword" placeholder="搜索医师姓名/科室/职称" @keyup.enter="() => loadData(1)" @blur="() => loadData(1)"
      class="search-input" type="text" />

    <!-- 错误信息提示 -->
    <div v-if="errorMsg" class="error-message">{{ errorMsg }}</div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary" role="status"
        aria-label="加载中"></div>
    </div>

    <!-- 数据内容区域 -->
    <div v-else>
      <!-- 表格主体 -->
      <div class="table-container">
        <table class="doctor-table-content">
          <thead>
            <tr>
              <th>医师ID</th>
              <th>用户ID</th>
              <th>姓名</th>
              <th>科室</th>
              <th>职称</th>
              <th>联系方式</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="doctor in doctors" :key="doctor.id" class="table-row" @click="openViewDialog(doctor)">
              <td>{{ doctor.id }}</td>
              <td>{{ doctor.userId || '未绑定用户' }}</td>
              <td>{{ doctor.name }}</td>
              <td>{{ doctor.department || '未分配科室' }}</td>
              <td>{{ doctor.title || '未设置职称' }}</td>
              <td>{{ doctor.phone || '未提供' }}</td>
              <td>{{ formatDate(doctor.createTime) }}</td>
              <td class="table-actions">
                <button class="btn-icon btn-view" @click.stop="resetPassword(doctor.id)">
                  <i class="fa fa-eye"></i>重置
                </button>
                <button class="btn-icon btn-edit" @click.stop="openEditDialog(doctor)">
                  <i class="fa fa-edit"></i>编辑
                </button>
                <button class="btn-icon btn-delete" @click.stop="handleDelete(doctor.id)">
                  <i class="fa fa-trash"></i>删除
                </button>
              </td>
            </tr>
            <tr v-if="doctors.length === 0" class="empty-row">
              <td colspan="7" class="text-center">未找到相关医师信息</td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-container" v-if="total > 0">
        <div class="pagination-info">
          共 {{ total }} 条记录，当前第 {{ currentPage }} 页
        </div>
        <div class="pagination-buttons">
          <button :disabled="currentPage === 1" @click="handlePageChange(1)">首页</button>
          <button :disabled="currentPage === 1" @click="handlePageChange(currentPage - 1)">上一页</button>
          <button v-for="page in visiblePages" :key="page"
            :class="currentPage === page ? 'btn-pagination active' : 'btn-pagination'"
            @click="handlePageChange(page)">{{ page }}</button>
          <button :disabled="currentPage === totalPages" @click="handlePageChange(currentPage + 1)">下一页</button>
          <button :disabled="currentPage === totalPages" @click="handlePageChange(totalPages)">末页</button>
        </div>
      </div>

      <!-- 空数据提示（当total=0且不是加载状态时显示） -->
      <div class="empty-container" v-else>
        <div class="empty-content">
          <i class="fa fa-inbox text-3xl mb-2 text-gray-300"></i>
          <p class="text-gray-500">未找到相关医师信息</p>
        </div>
      </div>
    </div>

    <!-- 添加/编辑医师对话框 -->
    <div v-if="dialogVisible" class="dialog-container" @click.self="dialogVisible = false">
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>{{ isEdit ? '编辑医师' : '添加医师' }}</h3>
          <button @click="dialogVisible = false" class="close-btn">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <form class="doctor-form">
            <div class="form-group">
              <label for="name">姓名</label>
              <input id="name" type="text" v-model="currentDoctor.name" required class="form-input">
            </div>
            <div class="form-group">
              <label for="department">科室</label>
              <input id="department" type="text" v-model="currentDoctor.department" class="form-input">
            </div>
            <div class="form-group">
              <label for="title">职称</label>
              <input id="title" type="text" v-model="currentDoctor.title" class="form-input">
            </div>
            <div class="form-group">
              <label for="phone">联系方式</label>
              <input id="phone" type="text" v-model="currentDoctor.phone" class="form-input">
            </div>
            <div class="form-group">
              <label for="userId">用户ID</label>
              <input id="userId" type="number" v-model="currentDoctor.userId" class="form-input">
            </div>
          </form>
        </div>
        <div class="dialog-footer">
          <button @click="dialogVisible = false" class="btn-cancel">取消</button>
          <button @click="saveDoctor" :class="isEdit ? 'btn-update' : 'btn-save'">
            {{ isEdit ? '更新' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 查看医师详情对话框 -->
    <div v-if="viewDialogVisible" class="dialog-container" @click.self="viewDialogVisible = false">
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>医师详情</h3>
          <button @click="viewDialogVisible = false" class="close-btn">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <div class="detail-item">
            <span class="detail-label">姓名：</span>
            <span class="detail-value">{{ viewedDoctor.name }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">用户ID：</span>
            <span class="detail-value">{{ viewedDoctor.userId || '未绑定用户' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">科室：</span>
            <span class="detail-value">{{ viewedDoctor.department || '未分配科室' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">职称：</span>
            <span class="detail-value">{{ viewedDoctor.title || '未设置职称' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">联系方式：</span>
            <span class="detail-value">{{ viewedDoctor.phone || '未提供' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">创建时间：</span>
            <span class="detail-value">{{ formatDate(viewedDoctor.createTime) }}</span>
          </div>
        </div>
        <div class="dialog-footer">
          <button @click="viewDialogVisible = false" class="btn-close">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'

// 状态变量
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const doctors = ref([])
const loading = ref(false)
const errorMsg = ref('')

// 对话框控制
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const viewedDoctor = ref({});

const currentDoctor = ref({
  id: null,
  name: '',
  department: '',
  title: '',
  phone: '',
  userId: null
})



// 计算分页
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

const visiblePages = computed(() => {
  if (totalPages.value <= 5) {
    return Array.from({ length: totalPages.value }, (_, i) => i + 1)
  }
  let start = currentPage.value - 2
  let end = currentPage.value + 2
  if (start < 1) {
    start = 1
    end = 5
  } else if (end > totalPages.value) {
    end = totalPages.value
    start = end - 4
  }
  return Array.from({ length: end - start + 1 }, (_, i) => start + i)
})

// 打开查看医生对话框
const openViewDialog = (doctor) => {
  viewedDoctor.value = { ...doctor };
  viewDialogVisible.value = true;
};

// 加载数据
const loadData = async (page) => {
  console.group('医师数据加载');
  page = page || currentPage.value;
  loading.value = true;
  errorMsg.value = '';
  
  try {
    // 明确请求路径为 /api/doctors/page
    const response = await axios.get('/api/doctors/page', {
      params: {
        pageNum: page,
        pageSize: pageSize.value,
        keyword: searchKeyword.value
      }
    });

    console.log('响应数据:', response.data);
    
    // 解析响应数据（假设后端返回格式为 { data: { records: [...], total: 100 } }）
    const data = response.data.data;
    doctors.value = data.records || [];
    total.value = data.total || 0;
    currentPage.value = page;
    
    console.log(`成功加载 ${doctors.value.length} 条数据`);
    console.log('total:', total.value);
    console.log('totalPages:', totalPages.value);
    console.log('visiblePages:', visiblePages.value);

  } catch (error) {
    console.error('请求失败:', error);
    if (error.response) {
      console.error('响应错误:', error.response.data);
      console.error('状态码:', error.response.status);
      errorMsg.value = `请求错误 (${error.response.status}): ${error.response.data.message || '接口异常'}`;
    } else {
      errorMsg.value = '网络错误，请检查连接';
    }
  } finally {
    loading.value = false;
    console.groupEnd();
  }
};


// 格式化时间
const formatDate = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit'
  })
}

// 弹窗控制
const openAddDialog = () => {
  isEdit.value = false
  currentDoctor.value = { id: null, name: '', department: '', title: '', phone: '' }
  dialogVisible.value = true
}

const openEditDialog = (doctor) => {
  isEdit.value = true
  currentDoctor.value = { ...doctor }
  dialogVisible.value = true
}

// 重置密码
const resetPassword = async (doctorId) => {
  if (!confirm('确定要将该医师的密码重置为默认值吗？')) return;
  
  try {
    // 调用后端API
    await axios.post('/api/password/reset-password', null, {
      params: { userId: doctorId }
    });
    
    // 显示成功消息
    errorMsg.value = '密码已重置为默认值';
    setTimeout(() => errorMsg.value = '', 3000);
  } catch (error) {
    console.error('重置密码失败', error);
    errorMsg.value = error.response?.data?.message || '重置密码失败，请重试';
  }
};

// 保存医师
const saveDoctor = async () => {
  if (!currentDoctor.value.name.trim()) {
    errorMsg.value = '姓名不能为空'
    return
  }
  try {
    if (isEdit.value) {
      await axios.put('/api/doctors', currentDoctor.value)
    } else {
      await axios.post('/api/doctors/new', currentDoctor.value)
    }
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('保存失败', error)
    errorMsg.value = isEdit.value ? '更新失败' : '添加失败'
  }
}

// 删除医师
const handleDelete = async (id) => {
  if (confirm('确定要删除该医师吗？此操作不可恢复')) {
    try {
      await axios.delete(`/api/doctors/${id}`)
      loadData()
    } catch (error) {
      console.error('删除失败', error)
      errorMsg.value = '删除失败'
    }
  }
}

// 页码跳转
const handlePageChange = (page) => {
  if (page < 1 || page > totalPages.value) return
  loadData(page)
}

// 初始加载
onMounted(() => {
  loadData()
})
</script>


<style scoped>
.error-message {
  color: #e74c3c;
  margin-bottom: 12px;
  font-size: 14px;
}
/* 基础容器样式 */
.doctor-table {
  width: 100%;
  padding: 24px;
  box-sizing: border-box;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
/* 按钮样式 */
.btn-add {
  background-color: white;
  color: rgb(0, 0, 0);
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: background-color 0.3s;
}

.btn-add:hover {
  background-color: #dceef9;
}
/* 搜索框样式 */
.search-container {
  margin-bottom: 20px;
  position: relative;
}

.search-input {
  width: 100%;
  padding: 12px 12px;
  padding-left: 32px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
  box-sizing: border-box;
  margin-bottom: 18px;
}

.search-input:focus {
  outline: none;
  border-color: #2980b9;
  box-shadow: 0 0 0 2px rgba(41, 128, 185, 0.2);
}

.search-input::placeholder {
  color: #95a5a6;
}

/* 加载状态样式 */
.loading-container {
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #95a5a6;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  overflow-x: auto;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 表格基础样式 */
.doctor-table-content {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.doctor-table-content th,
.doctor-table-content td {
  border: 1px solid #e0e0e0;
  padding: 12px;
  text-align: left;
  font-size: 14px;
  word-break: break-word;
}

.doctor-table-content th {
  background-color: #f5f5f5;
  font-weight: bold;
  color: #2c3e50;
}

.table-row {
  transition: background-color 0.2s;
}

.table-row:hover {
  background-color: #f9f9f9;
}

.table-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 6px;
}

.btn-icon {
  border: none;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s;
}
/* 按钮颜色区分 */
.btn-reset {
  background-color: #f39c12;
  color: white;
}

.btn-reset:hover {
  background-color: #e67e22;
}

.btn-edit {
  background-color: #e8f5ee;
  color: #27ae60;
}

.btn-edit:hover {
  background-color: #2980b9;
}

.btn-delete {
  color: #e74c3c;
  background-color: #ffebee;
}

.btn-delete:hover {
  background-color: #c0392b;
}


.empty-row {
  color: #7f8c8d;
  font-style: italic;
  text-align: center;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  font-size: 14px;
  color: #555;
}

.pagination-info {
  flex: 1;
}

.pagination-buttons {
  display: flex;
  gap: 4px;
}

.pagination-buttons button {
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  background-color: white;
  transition: all 0.3s;
  font-size: 14px;
  min-width: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-buttons button:hover:not(:disabled) {
  border-color: #2980b9;
  color: #2980b9;
}

.pagination-buttons button:disabled {
  border-color: #eee;
  color: #aaa;
  cursor: not-allowed;
}

.btn-pagination.active {
  background-color: #2980b9;
  color: white;
  border-color: #2980b9;
}

/* 对话框样式 */
.dialog-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 6px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.dialog-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.close-btn {
  border: none;
  background: none;
  font-size: 20px;
  cursor: pointer;
  color: #95a5a6;
}

.dialog-body {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.detail-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.detail-label {
  font-weight: bold;
  color: #555;
  width: 80px;
  display: inline-block;
}

.detail-value {
  color: #333;
}

.doctor-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  color: #555;
  font-size: 14px;
}

.form-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn-cancel, .btn-close {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  background-color: white;
  transition: all 0.3s;
}

.btn-save, .btn-update {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  color: white;
  transition: all 0.3s;
}

.btn-save {
  background-color: #2980b9;
}

.btn-update {
  background-color: #27ae60;
}

.btn-save:hover {
  background-color: #2573a8;
}

.btn-update:hover {
  background-color: #2ecc71;
}

.btn-cancel:hover, .btn-close:hover {
  border-color: #95a5a6;
  color: #555;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .doctor-table {
    padding: 12px;
  }
  
  .header-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .pagination-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .dialog-content {
    width: 90%;
  }
}
/* 在移动端压缩显示为图标 */
@media (max-width: 600px) {
  .btn-action span {
    display: none;
  }
}
</style>